<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">+新增</el-button>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="请输入">
        <el-input v-model="formInline.keyword" placeholder="请输入用户名"  />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="list" style="width: 100%;height: 500px;">
      <el-table-column 
        v-for="item in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 125"
      />
      <el-table-column fixed="right" label="操作" min-width="180">
        <template #default="scope">
          <el-button  type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button  type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="config.total"
      class="pager mt-4"
      @current-change="changePage"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    width="45%"
    :before-close="handleClose"
  >
    <el-form :inline="true" :model="formUser" class="demo-form-inline" ref="userForm">
      <!-- <el-row>
        <e-col :span="12">xxx</e-col>
        <e-col :span="12">xxx</e-col>
      </el-row> -->
      <el-form-item label="姓名" prop="name" 
        :rules="[{ required: true,message: '姓名是必填的',trigger: 'blur', },]"
      >
        <el-input v-model="formUser.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="年龄" prop="age"
        :rules="[
          {required: true,message: '年龄是必填的',trigger: 'blur',},
          {type:'number',message:'年龄是数字的'}
        ]"
      >
        <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
      </el-form-item>
      <el-form-item label="性别" prop="sex" :rules="[{required: true,message: '性别是必填的',trigger: 'change',},]">
        <el-select v-model="formUser.sex" placeholder="请选择性别">
          <el-option label="男" :value="0" />
          <el-option label="女" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birth" :rules="[{required: true,message: '出生日期是必填的',trigger: 'blur',}]">
        <el-date-picker
          v-model="formUser.birth"
          type="date"
          placeholder="请选择出生日期"
        />
      </el-form-item>
      <el-form-item label="地址" prop="addr" :rules="[{required: true,message: '性别是必填的',trigger: 'blur',},]"> 
        <el-input v-model="formUser.addr" placeholder="请输入年龄" />
      </el-form-item>
      <el-row style="justify-content: flex-end;">
        <el-form-item>
          <el-button type="primary" @click="onCancel">取消</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <!-- <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确定</el-button>
      </span>
    </template> -->
  </el-dialog>
</template>

<script>
import { defineComponent, getCurrentInstance, onMounted, reactive, ref } from 'vue'

export default defineComponent({
  setup(){
    const { proxy } = getCurrentInstance()
    const list = ref([])
    const tableLabel = reactive([
      {prop:'name',label:'姓名'},
      {prop:'age',label:'年龄'},
      {prop:'sexLabel',label:'性别'},
      {prop:'birth',label:'出生日期',width:200},
      {prop:'addr',label:'地址',width:320},
    ])
    const config = reactive({
      total:0,
      page:1,
      name:''
    })
    const formInline = reactive({
      keyword:'',
    })
    let dialogVisible = ref(false)
    const formUser = reactive({
      name:'',
      age:'',
      sex:'',
      birth:'',
      addr:''
    })
    let action = ref('add')

    onMounted(()=>{
      getUserData(config)
    })

    const getUserData = async (config)=>{
      let res = await proxy.$api.getUserData(config)
      //console.log(res);
      /* axios.get('api/user/getUser').then(res => {
        console.log(res);
      }) */
      config.total = res.count / 2
      list.value = res.list.map(item => {
        item.sexLabel = item.sex === 0 ? '女' : '男'
        return item
      })
    }
    const changePage =(page)=>{
      //console.log(page);
      config.page = page
      getUserData(config)
    }
    const handleSearch =()=>{
      config.name = formInline.keyword
      getUserData(config)
      config.name = ''
    }
    const handleClose = (done) => {
      ElMessageBox.confirm('确定关闭吗')
        .then(() => {
          proxy.$refs.userForm.resetFields()
          done() //即关闭
        })
        .catch(() => {
          // catch error
        })
    }
    const timeFormat =(time)=>{
      let now = new Date(time)
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      let date = now.getDate()
      function add(m){
        return m < 10 ? '0'+ m : m
      }
      return year + '-' + add(month) + '-' + add(date)
    }
    const onSubmit =()=>{
      proxy.$refs.userForm.validate( async (valid)=>{
        if(valid){
          if(action.value == 'add'){
            formUser.birth = timeFormat(formUser.birth)
            let res = await proxy.$api.addUser(formUser)
            //console.log(res);
            if(res){
              proxy.$refs.userForm.resetFields()
              dialogVisible.value = false
              getUserData(config)
            }
          }else{
            let res = await proxy.$api.editUser(formUser)
            if(res){
              proxy.$refs.userForm.resetFields()
              dialogVisible.value = false
              getUserData(config)
            }
          }
        }else{
          ElMessage.error('请输入完整的内容')
        }
      })
      /* formUser.birth = timeFormat(formUser.birth)
      let res = await proxy.$api.addUser(formUser)
      //console.log(res);
      if(res){
        //执行改方法需要添加prop属性
        proxy.$refs.userForm.resetFields()
        dialogVisible.value = false
        getUserData(config)
      } */
    }
    const onCancel =()=>{
      proxy.$refs.userForm.resetFields()
      dialogVisible.value = false
    }
    const handleAdd =()=>{
      action.value = 'add'
      dialogVisible.value = true
    }
    const handleEdit =(row)=>{
      action.value = 'edit'
      dialogVisible.value = true
      proxy.$nextTick(()=>{
        Object.assign(formUser,row)
      })
    }
    const handleDelete =(row)=>{
      ElMessageBox.confirm('确定删除吗')
        .then( async () => {
          await proxy.$api.deleteUser({id:row.id})
          ElMessage.success('删除成功')
          getUserData(config)
        })
        .catch(() => {
          // catch error
        })
    }
    return {
      list,
      tableLabel,
      config,
      changePage,
      formInline,
      handleSearch,
      dialogVisible,
      handleClose,
      formUser,
      onSubmit,
      onCancel,
      handleEdit,
      action,
      handleAdd,
      handleDelete
    }
  }
})
</script>

<style lang="less" scoped>
.user-header{
  margin-top: -20px;
  display: flex;
  justify-content: space-between;
}
.table{
  .pager{
    margin-top: 15px;
  }
  
}
</style>